import {
	baseUrl,
} from '@/serve/config.js'
const base64 = require('./base64_config')
const request = (options) => {
	// base64讲请求加密
	let currentTime = new Date().getTime() //获取当前时间戳
	let currentToken = null //拼接之后的token
	let encryptionToken = null //转码之后的token

	let useOptions = {
		url: baseUrl + options.url,
		method: options.method || 'GET',
		data: options.data || {},
		header: {
			'stype': 1,
			'tt': currentTime,
		}
	}
	// 获取token
	let userInfo = uni.getStorageSync('userInfo')
	if (userInfo && userInfo.token) {
		currentToken = userInfo.token + currentTime,
			encryptionToken = base64.encode(currentToken)
		useOptions.header.token = encryptionToken
	}
	return new Promise((resolve, reject) => {
		if (options.loading) {
			uni.showLoading({
				title: "加载中..."
			})
		}
		uni.request({
			...useOptions,
			timeout: 60000,
			success: (res) => {
				if (options.loading) {
					uni.hideLoading()
				}
				let statusCode = res.statusCode
				switch (statusCode) {
					// 添加请求拦截
					case 200:
						resolve(res.data)
						break;
					case 404:
						resolve(res.data)
						uni.showToast({
							title: res.data.error,
							icon: 'error'
						})
						break;
					case 502:
						resolve(res.data)
						uni.showToast({
							title: '服务已关闭',
							icon: 'error'
						})
					case 500:
						resolve(res.data)
						uni.showToast({
							title: '服务异常',
							icon: 'error'
						})
					default:
						resolve(res.data)
						uni.showToast({
							title: '数据请求失败',
							icon: 'error'
						})
				}
			},
			fail: (error) => {
				reject(error)
				uni.showToast({
					title: '网络错误！',
					icon: 'error'
				})
				if (options.loading) {
					uni.hideLoading()
				}
			}
		});
	})
}

export {
	request
}
